#include <functional>
#include "TcpClient.h"
#include "NetMgr.h"

class GlobalInit
{
public:
	GlobalInit()
	{
		NetMgr::GetInstance()->Init();
	};
};
static  GlobalInit g_GlobalInit;
TcpClient::TcpClient()
{
	m_readBuffer.resize(1024 * 64);
}

TcpClient::~TcpClient()
{
}

bool TcpClient::Connect(std::string ip, uint16_t port)
{
	m_task_scheduler = NetMgr::GetInstance()->m_oEventLoop.GetTaskScheduler();
	int ret = 0;
	do 
	{
		ret = m_AfTcpSocket.Open(true);
		if (ret != 0)
		{
			ret = -1;
			break;
		}
		ret = m_AfTcpSocket.Connect(AfSockAddr(ip.c_str(), port));
		if (ret != 0)
		{
			ret = -2;
			break;
		}

		ChannelPtr channel = std::make_shared<Channel>(m_AfTcpSocket.hSock);
		channel->SetReadCallback(std::bind(&TcpClient::OnRead, this));
		channel->EnableReading();
		ret = m_task_scheduler->UpdateChannel(channel);
		if (ret != 0)
		{
			ret = -3;
			break;
		}

	} while (0);
	return true;
}
void TcpClient::OnRead()
{
	int ret = m_AfTcpSocket.Recv(m_readBuffer.data(), 1024 * 64);
	if (ret > 0)
	{
		if (m_OnReadCallBack)
		{
			m_OnReadCallBack((int8_t*)m_readBuffer.data(), ret);
		}
	}
	printf("Recv... ret: ret_send: ret:%d \n", ret);

}

int TcpClient::Send(char* data, int len)
{
	int ret = m_AfTcpSocket.Send(data,len);
	return ret;
}